package org.brisling.duties.queryService;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.WhereUtil;
import org.brisling.duties.domain.ExecuteMonitor;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/executeMonitor/query")
public class QueryExecutemonitorService extends AbstractBaseQueryService<ExecuteMonitor>{
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryDictionaryService dicService;
	
	
	String warningDay ="14";
	String errorDay = "50";
	
	public QueryExecutemonitorService(){
		this.moduleName = ConstSysParam.MODULE_EXECUTEMONITOR;
		this.subSystem = ConstSysParam.SUBSYSTEM_DUTIES;
		this.tableName = ConstSysParam.VIEW_PREFIX +ConstSysParam.MODULE_EXECUTEMONITOR;
		this.clazz = ExecuteMonitor.class;
		
		typeMap = this.getTypeMap(clazz);
		
		
		orderMap.put("over_days","desc");
			
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<ExecuteMonitor> getListDomain(
			@RequestBody(required=false) String body){	
		
		
		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap,true);
		
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getStaticInfoAll.action")
	public LinkedHashMap getStaticInfoAll(@RequestBody(required=false) String body){
		LinkedHashMap map = new LinkedHashMap(); 
		
		map.put("inprocess", getStaticInprocessInfo(null));
		List<LinkedHashMap> lists = getTaskStatus();
		map.put("nodeMis", lists);
		map.put("flowMis",lists);
		return map;
	}
	
	/**
	 * 获取统计图表信息
	 * @param body	前端参数
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getStaticInfo.action")
	public List<LinkedHashMap> getStaticInfo(@RequestBody(required=false) String body){
		String sql = dicService.getSqlByBizcode("duties_chart_all");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> map = this.getBodyParam(body);
		
		Map<String,String> conditionMap = (Map<String, String>) map.get("condition");		
		
		if(!this.isSuperDept(userid,"query_all", "query_duties_all"))		
			conditionMap.put("doct_depart_code", SysConfig.getUsr(userid).getDeptid().toString());
		
		String whereCorse = WhereUtil.getConditionWhereCorse(conditionMap,typeMap);		
		whereCorse = (whereCorse==null)||(whereCorse.trim().length()<=0)?"":" where " + whereCorse;
		
		sql = String.format(sql, whereCorse);
		Integer page = map.containsKey("page")?LongUtil.getIntValue(map.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = map.containsKey("rows")?LongUtil.getIntValue(map.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return super.getPagedListMap(page, pageSize, sql);	
	}
	
	/**
	 * 获取统计图表信息
	 * @param body	前端参数
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	@RequestMapping("/getStaticInprocessInfo.action")
	public List<LinkedHashMap> getStaticInprocessInfo(@RequestBody(required=false) String body){
//		return getStaticOverdaysInfo(14,50,"inprocess","在办");
		
		String sql = dicService.getSqlByBizcode("duties_chart_progandfini");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> map = this.getBodyParam(body);
		
		Map<String,String> conditionMap = (Map<String, String>) map.get("condition");		
		
		if(!this.isSuperDept(userid,"query_all", "query_duties_all"))		
			conditionMap.put("doct_depart_code", SysConfig.getUsr(userid).getDeptid().toString());
		conditionMap.put("sxzt", "在办");
		String whereCorse = WhereUtil.getConditionWhereCorse(conditionMap,typeMap);		
		whereCorse = whereCorse==null?"":" where " + whereCorse;
		
		sql = String.format(sql,"inprocess",warningDay, errorDay,whereCorse);
		Integer page = map.containsKey("page")?LongUtil.getIntValue(map.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = map.containsKey("rows")?LongUtil.getIntValue(map.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return super.getPagedListMap(page, pageSize, sql);	
	}
	
	@SuppressWarnings("rawtypes")
	public List<LinkedHashMap> getTaskStatus(){
		String sql = "select '正常' as \"name\", count(*)as \"y\" from v_duties_execute_monitor  where sxzt = '办结'";
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,"query_all", "query_duties_all")){
			String deptids = this.getUserDeptids(userid);
			sql = sql + String.format(" and doct_depart_code in ('%1$s')",deptids); 
		}
		return super.getMappedList(sql);
	}
	
	/**
	 * 获取统计图表信息
	 * @param body	前端参数
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	@RequestMapping("/getStaticFinishiedInfo.action")
	public List<LinkedHashMap> getStaticFinishiedInfo(@RequestBody(required=false) String body){
		
		String sql = dicService.getSqlByBizcode("duties_chart_progandfini");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> map = this.getBodyParam(body);
		
		Map<String,String> conditionMap = (Map<String, String>) map.get("condition");		
		
		if(!this.isSuperDept(userid,"query_all", "query_duties_all"))		
			conditionMap.put("doct_depart_code", SysConfig.getUsr(userid).getDeptid().toString());
		conditionMap.put("sxzt", "办结");
		String whereCorse = WhereUtil.getConditionWhereCorse(conditionMap,typeMap);		
		whereCorse = whereCorse==null?"":" where " + whereCorse;
		
		sql = String.format(sql,"finished",warningDay, errorDay,whereCorse);
		Integer page = map.containsKey("page")?LongUtil.getIntValue(map.get("page").toString(),ConstSysParam.PAGE):ConstSysParam.PAGE;
		Integer pageSize = map.containsKey("rows")?LongUtil.getIntValue(map.get("rows").toString(),ConstSysParam.ROWS):ConstSysParam.ROWS;
		return super.getPagedListMap(page, pageSize, sql);		
	}
	
	/**
	 * 获取统计图表信息
	 * @param body	前端参数
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unused"})
	
	private List<LinkedHashMap> getStaticOverdaysInfo(Integer warningDay,Integer errorDay,String type,String state){
		String sql = "select issue_satus as \"name\",count(issue_satus) as \"y\",'%3$s' as \"issue_state\" from "
				+ "(select case when over_days<%1$d  then '正常' when over_days>=%1$d and over_days<=%2$d then '延时' when over_days>%2$d then '告警' end issue_satus from "
				+ this.getTableName()+" where sxzt='%4$s') group by issue_satus " ;
		sql = String.format(sql, warningDay,errorDay,type,state);
		return super.getMappedList(sql);
	}
	/**
	 * 获取统计图表信息
	 * @param body	前端参数
	 * @return List
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getOverdaysInfo.action")
	public List<LinkedHashMap> getOverdaysInfo(@RequestBody(required=false) String body){
		String sql = "select sxzt as \"name\",count(1)as \"y\" from  " + this.getTableName();
		Map<String,Object> map =getBodyParam(body);			
		
		String whereCorse = WhereUtil.getConditionWhereCorse((Map<String, String>) map.get("condition"),typeMap);
		
		if((whereCorse!=null)&&(whereCorse.trim().length()>0)){
			sql +=" where " + whereCorse;
		}
		sql += " group by sxzt";
		return super.getMappedList(sql);
	}
	
	/**
	 * 获取实体列表对象
	 * @param page
	 * @param rows
	 * @param deptid
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getList.action")
	public List<ExecuteMonitor> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public ExecuteMonitor getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public ExecuteMonitor getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	public void getRowCounts(String sql){
		super.getRowCount(sql);
	}
}
